package com.rzico.sbl.ui.report.manager

import android.graphics.Color
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDriverDetailBinding
import com.rzico.sbl.model.ManagerDate
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.viewmodel.ReportDriverViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.floatValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadCircleImage
import org.json.JSONObject

class ReportDriverDetailActivity : BaseActivity(R.layout.activity_report_driver_detail) {

    private val mBinding by lazy { ActivityReportDriverDetailBinding.bind(getRootView()) }

    private lateinit var mMemberId: String
    private val mBucketList = ArrayList<ManagerDate>()
    private val mOrderList = ArrayList<ManagerDate>()
    private var mBucketBeginDate = getBeforeDate(6)
    private var mBucketEndDate = getTodayDate()
    private var mOrderBeginDate = getBeforeDate(6)
    private var mOrderEndDate = getTodayDate()

    override fun getViewModel() = get<ReportDriverViewModel>()

    override fun initData() {
        initTitle(title = "司机详情")

        initLayout()

        getTotalData()
        getBucketData()
        getOrderData()
    }

    private fun initLayout() {
        mBinding.also {
            it.driverLine.apply {
                initChart(yAxisMinimum = 0f)

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mBucketList.indices) ""
                    else
                        mBucketList[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.driverBar.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mOrderList.indices) ""
                    else
                        mOrderList[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.driverName.text = intent.getExtra("name")
            it.driverPhone.text = intent.getExtra("phone")
            it.driverNum.text = intent.getExtra("count")
            it.driverImg.loadCircleImage(
                intent.getExtra("logo"),
                R.mipmap.default_logo3
            )
        }
    }

    /**
     * 监听方法
     */
    override fun initListener() {
        mMemberId = intent.getExtra("memberId")

        mBinding.apply {
            driverBarAll.oneClick {
                startActivityEx<ReportDriverOrderActivity>(
                    "memberId" to mMemberId,
                    "beginDate" to mOrderBeginDate,
                    "endDate" to mOrderEndDate
                )
            }

            driverLineTime.addTimeListener { start, end, _ ->
                mBucketBeginDate = start
                mBucketEndDate = end

                getViewModel().cancelRequest()
                getBucketData()
            }

            driverBarTime.addTimeListener { start, end, _ ->
                mOrderBeginDate = start
                mOrderEndDate = end

                getViewModel().cancelRequest()
                getOrderData()
            }
        }
    }

    /**
     * 设置空桶图表数据
     */
    private fun setBucketChart() {
        mBucketList.sumOf {
            it.quantity.intValue
        }.apply {
            mBinding
                .driverLineTotal
                .text = (this > 0)
                .conditionElseValue(
                    actionTrue = { " (总: ${this})" },
                    actionFalse = { "" }
                )
        }

        mBinding
            .driverLine
            .apply {
                (mBucketList.none { it.quantity.intValue > 0 })
                    .conditionElse(
                        actionTrue = ::clear,
                        actionFalse = {
                            setSingleData(
                                entries = mBucketList.mapIndexed { index, data ->
                                    Entry(
                                        index.toFloat(),
                                        data.quantity.floatValue
                                    )
                                },
                                lineColor = Color.parseColor("#A75FEA"),
                                labelColor = Color.parseColor("#FFD100"),
                                highColor = Color.parseColor("#A75FEA"),
                                drawableFill = R.drawable.fade_driver_num,
                                valueColor = Color.parseColor("#A75FEA"),
                                formatter = CustomValueFormatter()
                            )
                        }
                    )

                animateY(500)
            }
    }

    /**
     * 设置订单明细图表数据
     */
    private fun setOrderChart() {
        mBinding
            .driverBar
            .apply {
                if (mOrderList.none { it.quantity.intValue > 0 }) clear()
                else {
                    setGroupData(
                        entries = arrayListOf(
                            mOrderList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.quantity.floatValue
                                )
                            },
                            mOrderList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.amount.floatValue
                                )
                            },
                            mOrderList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.subQuantity.floatValue
                                )
                            }
                        ),
                        colorList = getViewModel().color4(),
                        labelList = listOf("固定水站", "转出订单", "转入订单"),
                        xFromValue = 0f,
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 获取本月数据
     */
    private fun getTotalData() {
        getViewModel()
            .request(
                isLoadingBefore = false,
                isLoadingAfter = false,
                requestUrl = ReportUrl.getBaseUrl().zDrisum,
                requestMethod = HttpMethod.GET,
                params = arrayOf(
                    "memberId" to mMemberId,
                    "beginDate" to getFirstDate(),
                    "endDate" to getEndDate()
                ),
                onSuccess = {
                    val obj = JSONObject(it)

                    mBinding.apply {
                        driverOrder.text = obj.optNotNull("quantity")
                        driverBucket.text = obj.optNotNull("subQuantity")
                    }
                }
            )
    }

    /**
     * 获取空桶图表数据
     */
    private fun getBucketData() {
        getViewModel()
            .bucketRange(
                memberId = mMemberId,
                beginDate = mBucketBeginDate,
                endDate = mBucketEndDate,
                onSuccess = {
                    mBucketList.clear()
                    mBucketList.addItems(it)

                    setBucketChart()
                }
            )
    }

    /**
     * 获取订单明细图表数据
     */
    private fun getOrderData() {
        getViewModel()
            .orderRange(
                memberId = mMemberId,
                beginDate = mOrderBeginDate,
                endDate = mOrderEndDate,
                onSuccess = {
                    mOrderList.clear()
                    mOrderList.addItems(it)

                    setOrderChart()
                }
            )
    }

}